package com.wejoy.video.middle.station.data.app;

import com.wejoy.video.middle.station.data.exception.BusinessException;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

/**
 * mybatis配置
 * @author admin
 */
@MapperScan("com.wejoy.video.middle.station.data.mapper")
@Configuration
public class MyBatisConfiguration {

    @Bean(name = "sessionFactory")
    public SqlSessionFactory sessionFactory(HikariDataSource dataSource) {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setDatabaseIdProvider(new VendorDatabaseIdProvider());
        bean.setTypeHandlersPackage("com.wejoy.video.middle.station.data.mybatis.type");

        //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            //设置xml扫描路径
            Resource[] baseMapperResource = resolver.getResources("classpath*:/mybatis/base-mapper.xml");
            Resource[] resources = resolver.getResources("classpath*:/mybatis/**/*.xml");
            Resource[] mapperLocations = ArrayUtils.addAll(resources, resources);
            bean.setMapperLocations(mapperLocations);
            return bean.getObject();
        } catch (Exception e) {
            throw new BusinessException("sessionFactory init fail",e);
        }
    }

    /**
     * 配置事务管理器
     */
    @Bean(name = "transactionManager")
    public DataSourceTransactionManager transactionManager(HikariDataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}